<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
  import echarts from 'echarts'

  require('echarts/theme/macarons') // echarts theme
  import {debounce} from '@/utils'


  const animationDuration = 1000

  export default {
    name: 'refer-chart',
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '300px'
      },
      xData: Array,
      yData: Array,
      // tooltipData: Array,
      opts: Object
    },
    data() {
      return {
        chart: null
      }
    },
    watch: {
      yData() {
        this.renderChart();
      }
    },
    mounted() {
      this.initChart()
      this.__resizeHanlder = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHanlder)
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHanlder)
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')
        this.renderChart()
      },
      renderChart() {
        const series = [
          {
            name: '访问来源',
            type: 'pie',
            radius: '55%',
            center: ['50%', 125],
            data: this.yData,
            itemStyle:{
                normal:{label:{show:false}},
                emphasis:{label:{show:true}}
              },
            //   .concat(
            //   [
            //   {value:335, name:'www.baidu.com'},
            //   {value:310, name:'baidu.com'},
            //   {value:234, name:'baidu.com'},
            //   {value:135, name:'baidu.com'},
            //   {value:1548, name:'baidu.com'}
            // ])
          }
        ];

        this.chart.setOption({
          // title : {
          //   // text: '某站点用户访问来源',
          //   // subtext: '纯属虚构',
          //   // x:'center'
          // },
          tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
          },
          calculable: true,
          legend: {
            orient: 'vertical',
            x: 'left',
            data: ['baidu', 'baidu', 'baidu', 'baidu', 'baidu']
          },

          series
        });
      }
    }
  }
</script>
